<?php

// +----------------------------------------------------------------------
// | Think.Admin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限企业 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/Think.Admin
// +----------------------------------------------------------------------

namespace app\common\service;

use think\facade\Config;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class QiniuService {

    public function up2QiNiuYun ($fileList,$old_name = false) {
        $file = request()->file($fileList);
        $accessKey = config('api.sevenniu.accessKey');
        $secretKey = config('api.sevenniu.secrectKey');
        $bucket = config('api.sevenniu.bucket');
        // 构建鉴权对象 #需要填写你的 Access Key 和 Secret Key
        $auth = new Auth($accessKey, $secretKey);
        // 生成上传 Token
        $token = $auth->uploadToken($bucket);
        // 要上传文件的本地路径
        $filePath = $file->getRealPath();
        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
        // 上传到七牛后保存的文件名
        if ($old_name){
            $key = $file->getInfo('name');
        }else{
            $key = substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
        }

        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();

        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return ['code'=>0,'msg'=>'上传失败','data'=> $err];
        } else {
            //返回图片名
            return  $key;
        }
    }

    public static function base64($base64, $key) {
        $accessKey = Config::get('qiniu.AccessKey');
        $secretKey = Config::get('qiniu.SecretKey');
        $bucket = Config::get('qiniu.Bucket');
        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);
        $uploadMgr = new UploadManager();
        // 上传字符串到七牛
        list($ret, $err) = $uploadMgr->put($token, $key, $base64);
        if ($err !== null) {
            return $err;
        } else {
            return $ret;
        }
    }


}